package com.example.hxpc.guidancemanagement.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.hxpc.guidancemanagement.R;
import com.example.hxpc.guidancemanagement.activity.AboutWeActivity;
import com.example.hxpc.guidancemanagement.activity.ChangeNameActivity;
import com.example.hxpc.guidancemanagement.activity.ChangePasswordActivity;
import com.example.hxpc.guidancemanagement.activity.MainActivity;
import com.example.hxpc.guidancemanagement.tools.LogoutT;
import com.example.hxpc.guidancemanagement.tools.ToastTools;
import com.example.hxpc.guidancemanagement.tools.mold.BasePopupWindow;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by tao on 2017/11/29.
 * 主页面-个人Frament
 */

public class MainPerFrament extends Fragment implements View.OnClickListener{
    private View rootView;
    private String type;
    private FrameLayout fram_1,fram_2;
    private RelativeLayout rela_change_head , rela_change_name , rela_change_password ,rela_about_we ,rela_log_out;
    private ImageView img_add , img_back , img_head;
    private TextView te_title;
    private Intent intent;
    private int screenHeight;
    private int screenWidth;
    private PopupWindow popupWindow;
    private Bitmap photo = null;
    private File file = null;

    /* 头像文件 */
    private static final String IMAGE_FILE_NAME = "temp_head_image.jpg";

    /* 请求识别码 */
    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;

    // 裁剪后图片的宽(X)和高(Y),480 X 480的正方形。
    private static int output_X = 128;
    private static int output_Y = 128;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null){
            rootView = inflater.inflate(R.layout.frament_main_person,null);
        }
        initView(rootView);
        LogoutT.logout(type);
        if(type.equals("3")){
            fram_1.setVisibility(View.VISIBLE);
            fram_2.setVisibility(View.GONE);
        }else{
            fram_1.setVisibility(View.GONE);
            fram_2.setVisibility(View.VISIBLE);
        }
        return rootView;
    }

    //初始化控件
    public void initView(View rootView){
        fram_1 = (FrameLayout) rootView.findViewById(R.id.fram_1);
        fram_2 = (FrameLayout) rootView.findViewById(R.id.fram_2);
        rela_change_head = (RelativeLayout) rootView.findViewById(R.id.person_rela_5);
        rela_change_head.setOnClickListener(this);
        rela_change_name = (RelativeLayout) rootView.findViewById(R.id.person_rela_1);
        rela_change_name.setOnClickListener(this);
        rela_change_password = (RelativeLayout) rootView.findViewById(R.id.person_rela_2);
        rela_change_password.setOnClickListener(this);
        rela_about_we = (RelativeLayout) rootView.findViewById(R.id.person_rela_3);
        rela_about_we.setOnClickListener(this);
        rela_log_out = (RelativeLayout) rootView.findViewById(R.id.person_rela_4);
        rela_log_out.setOnClickListener(this);
        img_add = (ImageView) rootView.findViewById(R.id.add_mark);
        img_add.setVisibility(View.GONE);
        img_back = (ImageView) rootView.findViewById(R.id.back);
        img_back.setVisibility(View.GONE);
        img_head = (ImageView) rootView.findViewById(R.id.img_head);
        te_title = (TextView) rootView.findViewById(R.id.te_title);
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        type = ((MainActivity)activity).getUserType();
    }

    //初始化popupwindow,用户点击提交按钮弹出窗口
    public void intiPopupWindow(View view, int i) {
        //获取屏幕高度和宽度
        WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
        screenHeight = wm.getDefaultDisplay().getHeight();
        screenWidth = wm.getDefaultDisplay().getWidth();
        popupWindow = new BasePopupWindow(view, screenWidth, screenHeight / i, true, true, true, true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
        popupWindow.update();
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });
    }

    //改变背景透明度
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getActivity().getWindow().setAttributes(lp);
    }

    //修改头像
    public void amendHeadPortrait(View view) {
        RelativeLayout re_take_photo = (RelativeLayout) view.findViewById(R.id.take_photo);
        RelativeLayout re_select_photo = (RelativeLayout) view.findViewById(R.id.select_photo);
        RelativeLayout re_cancel = (RelativeLayout) view.findViewById(R.id.cancel);
        re_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        re_take_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断是否有访问的权限
                /*if (ContextCompat.checkSelfPermission(ChangePersonInfo.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED){
                    LogoutT.logout("正在接收权限受理......");
                    ActivityCompat.requestPermissions(ChangePersonInfo.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            MY_PERMISSIONS_REQUEST_CALL_PHONE2);
                }else{
                    LogoutT.logout("以获取授权");
                    choseHeadImageFromCameraCapture();
                }*/
                choseHeadImageFromCameraCapture();
                popupWindow.dismiss();
            }
        });

        re_select_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //判断是否有访问的权限
                /*if (ContextCompat.checkSelfPermission(ChangePersonInfo.this,Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED){
                    LogoutT.logout("正在接收权限受理......");
                    ActivityCompat.requestPermissions(ChangePersonInfo.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            MY_PERMISSIONS_REQUEST_CALL_PHONE);
                }else{
                    LogoutT.logout("以获取授权");
                    choseHeadImageFromGallery();
                }*/
                choseHeadImageFromGallery();
                popupWindow.dismiss();
            }
        });
    }

    /**
     * 从本地相册选取图片作为头像
     */
    public void choseHeadImageFromGallery() {
        Intent intentFromGallery = new Intent();
        //设置文件类型
        intentFromGallery.setType("image/*");
        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intentFromGallery, CODE_GALLERY_REQUEST);
    }

    /**
     * 启动手机相机拍摄照片作为头像
     */
    public void choseHeadImageFromCameraCapture() {
        Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //判断存储卡是否可用，存储照片文件
        if (hasSdcard()) {
            intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME)));
        }else{
        }
        startActivityForResult(intentFromCapture, CODE_CAMERA_REQUEST);
    }


    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            //有存储的SDCard
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case CODE_GALLERY_REQUEST:
                cropRawPhoto(data.getData());
                break;
            case CODE_CAMERA_REQUEST:
                if (hasSdcard()) {
                    File tempFile = new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME);
                    cropRawPhoto(Uri.fromFile(tempFile));
//                    okHttpTools.setUserHead(this,tempFile);
                } else {
                    ToastTools.toastMsg(getActivity(),"没有SD卡");
                }
                break;
            case CODE_RESULT_REQUEST:
                if (data != null) {
                    setImageToHeadView(data);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 裁剪原始的图片
     *
     * @param uri
     */
    public void cropRawPhoto(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");

        //设置裁剪
        intent.putExtra("circleCrop", "true");
        //aspectX , aspectY : 宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        //outputX , outputY : 裁剪图片的高度
        intent.putExtra("outputX", output_X);
        intent.putExtra("outputY", output_Y);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CODE_RESULT_REQUEST);
    }

    /**
     * 提取保存裁剪之后的图片数据，并设置头像部分的View
     *
     * @param intent
     */
    public void setImageToHeadView(Intent intent) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            photo = extras.getParcelable("data");
            LogoutT.logout(getSDPath());
            saveBitmap(getSDPath(), "avatar.jpg", photo);
//            okHttpTools.setUserHead(this,file);
            img_head.setImageBitmap(photo);
        }
        LogoutT.logout(file.length() + "   111111");
        LogoutT.logout(file.getAbsolutePath());
    }

    /**
     * 获取SD卡的路径
     * @return
     */
    public String getSDPath() {
        File sdDir = null;
        //判断sd卡是否存在
        boolean sdCardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取根目录
        }
        return sdDir.toString();
    }

    /**
     * 保存Bitmap位图到指定位置中
     * @param path 文件路径
     * @param fileName 文件名称
     * @param bm 需要保存的Bitmap位图
     */
    public void saveBitmap(String path, String fileName, Bitmap bm) {
        file = new File(path, fileName);
        if (file.exists()) {
            file.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            LogoutT.logout("保存成功！");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.person_rela_1:
                ToastTools.toastMsg(getActivity(),"name");
                intent = new Intent(getActivity(), ChangeNameActivity.class);
                startActivity(intent);
                break;
            case R.id.person_rela_2:
                ToastTools.toastMsg(getActivity(),"password");
                intent = new Intent(getActivity(), ChangePasswordActivity.class);
                startActivity(intent);
                break;
            case R.id.person_rela_3:
                ToastTools.toastMsg(getActivity(),"about we");
                intent = new Intent(getActivity(), AboutWeActivity.class);
                startActivity(intent);
                break;
            case R.id.person_rela_4:
                ToastTools.toastMsg(getActivity(),"log out");
                break;
            case R.id.person_rela_5:
                ToastTools.toastMsg(getActivity(),"head");
                View view_change_head = LayoutInflater.from(getActivity()).inflate(R.layout.change_person_head,null);
                intiPopupWindow(view_change_head, 4);
                backgroundAlpha(0.7f);
                popupWindow.showAtLocation(getActivity().getLayoutInflater().inflate(R.layout.activity_main, null), Gravity.BOTTOM,
                        0, 0);
                amendHeadPortrait(view_change_head);
                break;
        }

    }
}
